<template>
  <div class="container">
    <div class="operate_list" v-show="!isShowChatRef">
      <div class="left" style="cursor: pointer;">
        <img src="@/assets/search/bz8.svg" alt="" @click.native='activeWeb' />
      </div>
      <div class="right">
        <el-tooltip class="box-item" effect="dark" :content="item.name" v-for="(item, index) in btnList" :key="item.name">
          <el-popconfirm v-if="item.name === '清空'" :width="200" hide-icon title="聊天记录不可恢复。确定清空？" confirm-button-text="确定" cancel-button-text="取消" @confirm="confirmEvent"
            @cancel="cancelEvent">
            <template #reference>
              <img class="box-img" :src="item.src" :style="item.style" alt="" />
            </template>
          </el-popconfirm>
          <img v-else class="box-img" :src="item.src" :style="item.style" alt="" @click.native='btnClick(item.name)' />
        </el-tooltip>
        <ClosePop type="search"></ClosePop>
      </div>
    </div>
    <!-- <div class="operate_list_no" v-show="isShowChatRef">
      <div class="operate_clear" @click.stop="clear">清除会话</div>
      <div class="operate_toTop" @click.stop="onTop"><img src="@/assets/search/bz10.svg" alt="" style="width:14px" />置顶
      </div>
    </div> -->
    <div class="shadow" :style="{paddingTop: isShowChatRef?'20px':'0'}">
      <div @click.stop="focusInput" ref="inputContainer" class="input_container" v-notDrag>
        <div ref="propmptRef" class="commen_tag propmpt" v-for="item in propmpt" :style="{ ...item.style }" :key="item.id" v-show="item.id">
          <img :src="item.icon" :alt="item.text" class="li_img_svg" />
          <span class="propmpt_text_close" @click="deletePropmpt(item.id)">{{ item.text }}</span>
        </div>
        <div ref="wrapper" class="wrapper">
          <input :disabled="isSending" :style="{cursor: isSending?'not-allowed':'unset'}" ref="input" @input="inputText" @keydown="keydownBack" @blur="blur" v-model="text" class="input"
            type="text" />
          <span @click="() => input?.focus()" class="placholder">{{
            placholder
          }}</span>
        </div>
        <div class="send" @click="sendMessage">
          <img src="@/assets/search/bz3.svg" @dragstart="(event) => event.preventDefault()" alt="" />
        </div>
      </div>

    </div>
    <ul @transitionend="isTransitioned" ref="drop" is-hidden="true" class="drop" v-notDrag>
      <li :style="{
        height: LI_HEIGHT + 'px',
        padding: '0 20px',
        lineHeight: LI_HEIGHT + 'px',
      }" v-for="item in propmpts" @mousedown="addPropmpt(item)">
        <div class="li_item">
          <img :src="item.icon" :alt="item.text" class="li_img" />
          <div style="line-height: 16px;margin-left: 10px;">{{ item.text }}</div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Propmpt } from "@/types";
import { isElectron } from "@/utils";
import { defineComponent, computed, ref, nextTick, reactive } from "vue";
import Operate from "./operate.vue";
import { chatWebUrl, clearConversation } from "@/utils/api.ts";
import ClosePop from "./closePop.vue"
import zoominImg from '@/assets/search/zoommin.svg';
import openChatImg from '@/assets/search/zoommax.svg';
import img10 from '@/assets/search/bz10.svg';
import img11 from '@/assets/search/bz11.svg';
import img12 from '@/assets/search/bz12.svg';

export default defineComponent({
  name: "PropmptSearch",
  emits: ["popupChat", "sending", "setBroseWinodwHeight", 'clearChat'],
  props: ["isShowChat","isSending"],
  components: {
    Operate,
    ClosePop
  },
  setup(props, ctx) {
    const LI_HEIGHT = 36;
    const input = ref<HTMLInputElement>();
    const wrapper = ref<HTMLElement>();
    const propmptRef = ref<HTMLElement[]>();
    const inputContainer = ref<HTMLElement>();
    const drop = ref<HTMLElement>();
    const text = ref("");
    const isShowChatRef = computed(() => props.isShowChat);
    const btnList = ref([{ name: '置顶', src: img10, style:{} },
    { name: '清空', src: img11, style:{} },
    { name: '设置', src: img12, style:{} },
    { name: '最小化', src: zoominImg, style:{}},
    { name: '展开', src: openChatImg, style:{} },
  ]);
    const propmpt = reactive<Array<Propmpt>>([]);
    const placholder = ref("快来向我提问吧，猜你想要……");
    let isTransition = false;
    let timer: any = null;

    let propmpts = ref(
      JSON.parse(localStorage.getItem("propmpts") || "null") || []
    );
    function deletePropmpt(id: string) {
      let index = propmpt.findIndex((value) => value.id === id);
      trendDelPropmpt(index);
      setPlacholder();
    }
    function addPropmpt(cur: Propmpt) {
      propmpt.splice(0, 1, cur);
      let width = 0;
      nextTick(() => {
        if (propmptRef.value && wrapper.value) {
          propmptRef.value.map((tag) => {
            width += tag.getBoundingClientRect().width;
          });
          wrapper.value.style.left = `
           ${width + 20}px
         `;
        }
      });
      localStorage.setItem("curPropmpt", JSON.stringify(cur));
      setPlacholder();
      setTimeout(() => {
        input.value?.focus();
      }, 300);
    }
    function filterPropmpt() {
      if (propmpt.length <= 0) {
        propmpts.value = propmpts.value.filter((value: Propmpt) =>
          value.text.includes(text.value)
        );
        if (drop.value) {
          drop.value.style.height = propmpts.value.length * LI_HEIGHT + "px";
        }
      }
    }
    function inputText(e: Event) {
      const value = (e.target as HTMLInputElement).value;
      text.value = value;
      if (value.trim().length > 0) {
        setPlacholder();
      } else {
        setPlacholder();
      }
    }
    function focusInput(e: any) {
      //点击send不出现下拉菜单
      console.log(e.target.className)
      if ((e.target as HTMLDivElement).className === "propmpt_text") return;
      if (!e.target.className) return;
      if (propmpt.length >= 1) return;

      input.value?.focus();
      const isHidde = drop.value?.getAttribute("is-hidden");

      if (!isTransition) {
        isTransition = true;
        if (drop.value) {
          clearTimeout(timer);
          if (isHidde === "true") {
            ctx.emit("setBroseWinodwHeight");
            drop.value.style.maxHeight = "200px";
            drop.value.style.height = propmpts.value.length * LI_HEIGHT + "px";
            drop.value.style.border = "1px solid #e4e7ed";
            drop.value.style.padding = "10px";
            drop.value.setAttribute("is-hidden", "false");
          } else {
            drop.value.style.height = "0";
            drop.value.style.padding = "0";
            drop.value.style.border = "none";

            timer = setTimeout(() => {
              ctx.emit("setBroseWinodwHeight");
              drop.value?.setAttribute("is-hidden", "true");
              if (isTransition) isTransition = false;
            }, 600);
          }
        }
      }
    }
    function keydownBack(e: KeyboardEvent) {
      // console.log(e.code,propmpt,text.value)
      if (
        e.code === "Backspace" &&
        propmpt.length > 0 &&
        text.value.trim().length === 0
      ) {
        trendDelPropmpt(propmpt.length - 1);
        setPlacholder();
      }

      if (
        e.code === "Enter" &&
        text.value.trim().length > 0
      ) {
        sendMessage(e);
      }
    }
    function setPlacholder() {
      if (text.value.trim().length > 0) {
        placholder.value = "";
      } else {
        if (propmpt.length > 0) {
          placholder.value = propmpt[0].text;
        } else {
          placholder.value = "快来向AI小助手提问吧,猜你想做,从下方选择......";
        }
      }
    }
    function blur() {
      bodyClick();
    }
    function bodyClick() {
      if (!isTransition) {
        clearTimeout(timer);
        if (drop.value) {
          drop.value.style.height = "0";
          drop.value.style.padding = "0";
          drop.value.style.border = "none";

          timer = setTimeout(() => {
            ctx.emit("setBroseWinodwHeight", "send");
            drop.value?.setAttribute("is-hidden", "true");
          }, 600);
        }
      }
    }
    function trendDelPropmpt(index: number) {
      if (wrapper.value && propmptRef.value) {
        propmpt.splice(index, 1);
        wrapper.value.style.left = `${wrapper.value.offsetLeft -
          propmptRef.value[index].getBoundingClientRect().width -
          10
          }px`;
      }
    }
    function isTransitioned() {
      isTransition = false;
    }

    function openChat() {
      ctx.emit("popupChat");
      ctx.emit("setBroseWinodwHeight");
      onTop();
    }

    function miniSize() {
      ctx.emit("miniSize");
    }

    function btnClick(name: any) {
      if (name === '置顶') onTop();
      if (name === '展开') openChat();
      if (name === '最小化') miniSize();
      if (name === '设置') setting();
    }

    async function sendMessage(_: Event) {
      if (text.value.trim().length === 0) return;
      nextTick(() => {
        onTop()
      })
      clearTimeout(timer);
      const isHidde = drop.value?.getAttribute("is-hidden");
      ctx.emit("popupChat");
      localStorage.setItem("selectedText", text.value.toString());
      ctx.emit("sending", {
        propmpt: { ...propmpt[0] },
        text: text.value,
      });
      if (isHidde === "true" || !props.isShowChat) {
        ctx.emit("setBroseWinodwHeight", "send");
      } else {
        timer = setTimeout(() => {
          ctx.emit("setBroseWinodwHeight", "send");
        }, 600);
      }
      if (propmpt.length > 0) deletePropmpt(propmpt[0].id);
      text.value = "";
      setPlacholder();
    }

    function setting() {
      ctx.emit('setting');
    }
    function onTop() {
      if (!isElectron()) return
      const { ipcRenderer } = require("electron");
      ipcRenderer.invoke("onTop");
    }

    const confirmEvent = async () => {
      const userInfo = JSON.parse(localStorage.getItem("userInfo") || "null");
      const currParam = {
        "category": userInfo.category,
        "kind": userInfo.kind,
        "convId": userInfo.convId,
      }
      const info = await clearConversation(currParam);
      if (info.msg === 'success') {
        userInfo.convId = info.data.convId;
        localStorage.setItem("userInfo", JSON.stringify(userInfo) || '');
        clear();
      }
    }
    const cancelEvent = () => {
      console.log('cancel!')
    }
    function clear() {
      ctx.emit('clearChat')
    }
    function activeWeb() {
      ctx.emit('activeWeb')
    }

    function updateInput(curPropmpt: any, selectedText: string) {
      curPropmpt && addPropmpt(curPropmpt);
      text.value = selectedText;
      setPlacholder();
    }

    function copyQuestion(opt: any) {
      updateInput(opt.propmpt || propmpts.value[0], opt.text || '')
    }

    if (isElectron()) {
      const { ipcRenderer } = require("electron");
      ipcRenderer.on("preSend", (_: any, data: any) => {

        let selectedText = data.selectedText;
        console.log(selectedText)
        let curPropmpt = JSON.parse(
          localStorage.getItem("curPropmpt") || "null"
        );

        updateInput(curPropmpt, selectedText)
      });
    }

    document.body.addEventListener("click", bodyClick);

    // window.addEventListener('setItemEvent', function (e: any) {
    //   if (e.key === 'tableData') {   // tableData 是需要监听的键名
    //     console.log(JSON.parse(e.newValue))   // 这里的newValue就是localStorage中，键名为tableData对应的变化后的值。
    //   }
    // })

    return {
      isShowChatRef,
      activeWeb,
      btnClick,
      clear,
      isTransitioned,
      input,
      wrapper,
      inputContainer,
      drop,
      propmpt,
      deletePropmpt,
      propmpts,
      addPropmpt,
      inputText,
      focusInput,
      LI_HEIGHT,
      btnList,
      text,
      filterPropmpt,
      keydownBack,
      placholder,
      propmptRef,
      sendMessage,
      blur,
      setting,
      onTop,
      confirmEvent,
      cancelEvent,
      copyQuestion
    };
  },
});
</script>
<style scoped lang="scss">
ul li {
  list-style-type: none;
  background-color: white;
}

li:hover {
  background: rgba(37, 103, 240, 0.1);
  border-radius: 6px;
}

.li_img {
  width: 16px;
  height: 16px;
}

.li_item {
  display: flex;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333333;
  align-items: center;
  height: 36px;
}

.container {
  background-color: #f3f5fd;
  border-radius: 10px;
  position: relative;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);

  .right {
    display: flex;
    margin-top: 6px;
  }

  .box-img {
    width: 22px;
    height: 22px;
    margin-left: 16px;
    cursor: pointer;
  }

  .operate_list {
    display: flex;
    padding: 10px 20px;
    height: 47px;
    justify-content: space-between;
  }

  .operate_list_no {
    display: flex;
    padding: 20px;
  }

  .operate_clear {
    width: 80px;
    height: 34px;
    background: linear-gradient(270deg, #2567F0 0%, #4C91F9 100%);
    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #FFFFFF;
    line-height: 34px;
    text-align: center;
    cursor: pointer;
  }

  .operate_toTop {
    width: 80px;
    height: 34px;
    margin-left: 20px;
    background: white;
    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    line-height: 34px;
    text-align: center;
    cursor: pointer;
    display: flex;
    justify-content: center;
  }

  .shadow {
    position: relative;
    display: flex;
    padding: 20px;
    box-sizing: border-box;
  }

  .send {
    // display: flex;
    position: absolute;
    right: 20px;
    align-items: center;
    padding-left: 10px;

    img {
      width: 28px;
      height: 28px;
      box-sizing: border-box;
      cursor: pointer;
    }
  }

  .draw {
    height: 100%;
    width: 100%;
    position: absolute;
    left: 10px;
    top: 0;
  }

  .logo {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    position: relative;
    user-select: none;

    img {
      width: 100%;
      height: 100%;
      user-select: none;
      -moz-user-select: none;
      -webkit-user-select: none;
    }
  }

  .drop {
    margin: 0 20px;
    margin-top: -14px;
    left: 0;
    right: 0;
    box-sizing: border-box;
    position: absolute;
    height: 0;
    transition: height 0.5s;
    overflow: auto;
    background: #FFFFFF;
    box-shadow: 0px 0px 4px 4px rgba(233, 233, 233, 0.5);
    border-radius: 10px;

    li {
      box-sizing: border-box;
    }

    &::-webkit-scrollbar {
      width: 3px;
      /* 设置滚动条宽度 */
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 6px;
      background-color: rgb(204, 204, 204);
      /* 设置滚动条颜色 */
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
      margin-top: 10px;
      margin-bottom: 10px;
      /* 设置滚动条背景色 */
    }
  }

  .input_container {
    display: flex;
    flex: 1;
    align-items: center;
    // border: 1px solid #ccc;
    cursor: text;
    background-color: #fff;
    height: 60px;
    border-radius: 10px;
    overflow: hidden;
    position: relative;
    box-shadow: 0px 0px 4px 4px rgba(146, 208, 253, 0.2);
    z-index: 2;

    .commen_tag {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      background-color: #fff;
      position: absolute;
      left: 10px;
      z-index: 1;
    }

    .propmpt {
      background: rgba(37, 103, 240, 0.1);
      border-radius: 6px;
      padding: 8px 13px;

      .close {
        position: absolute;
        font-size: 18px;
        right: 5px;
        cursor: pointer;
        color: #ccc;
      }

      .li_img_svg {
        position: relative;
        // transform: translateX(-80px);
        // filter: drop-shadow(#2567F0 80px 0);
        // border-left: 4px solid transparent; //防止drop-shadow主体超出视线隐藏后阴影消失
        // border-right: 4px solid transparent;
      }

      .propmpt_text_close {
        margin-left: 8px;
        color: #2567F0;
        cursor: pointer;
      }
    }

    .wrapper {
      position: absolute;
      display: flex;
      align-items: center;
      transition: left 0.3s;
      left: 10px;
      right: 50px;
      top: 50%;
      transform: translateY(-50%);

      .input {
        width: 100%;
        outline: none;
        border: none;
        font-size: 16px;
        padding-right: 20px;
        height: 100%;
        background-color: transparent;
        z-index: 1;
      }

      .placholder {
        position: absolute;
        color: #a8abb2;
        user-select: none;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
      }
    }
  }
}
</style>
